package com.mashibing.servicedriveruser.service;

import com.mashibing.internalcommon.dto.Car;
import com.mashibing.internalcommon.dto.ResponseResult;
import com.mashibing.internalcommon.response.TerminalResponse;
import com.mashibing.internalcommon.response.TrackResponse;
import com.mashibing.servicedriveruser.mapper.CarMapper;
import com.mashibing.servicedriveruser.remote.ServiceMapClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 史慕尧
 */
@Service
public class CarService {
    @Autowired
    CarMapper carMapper;

    @Autowired
    ServiceMapClient serviceMapClient;

    public ResponseResult addCar(Car car) {
        LocalDateTime now = LocalDateTime.now();
        car.setGmtCreate(now);
        car.setGmtModified(now);
        carMapper.insert(car);
        /////////////调用创建终端车辆的函数，返回tid和car一起存入数据库
        ResponseResult<TerminalResponse> responseResult = serviceMapClient.addTerminal(car.getVehicleNo(), car.getId() + "");
        String tid = responseResult.getData().getTid();
        car.setTid(tid);
        ////////////获得车辆的轨迹id
        ResponseResult<TrackResponse> trackResponseResponseResult = serviceMapClient.addTrack(car.getTid());
        String trid = trackResponseResponseResult.getData().getTrid();
        car.setTrid(trid);
        carMapper.updateById(car);
        return ResponseResult.success("");
    }

    public ResponseResult<Car> getCarById(String carId) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", carId);
        List<Car> cars = carMapper.selectByMap(map);
        return ResponseResult.success(cars.get(0));
    }
}
